package com.ftg.learn.mybatis.chapter1.dao;

import com.ftg.learn.jdbc.chapter01.vo.EmpAndDept;
import com.ftg.learn.mybatis.chapter1.entity.Dept;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * mybatis 通用测试类
 * @author kangjx
 * @createTime 2022/10/8
 */
public class DeptDao {

    private SqlSession session = null;

    {
        String resource = "mybatisconfig.xml";

        Reader inputStream = null;
        try {

            inputStream = Resources.getResourceAsReader(resource);
            SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
            SqlSessionFactory ssf = ssfb.build(inputStream);
            if(Objects.isNull(this.session)){
                this.session = ssf.openSession();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得session操作
     * @return
     */
    public SqlSession getSession(){
        if(Objects.isNull(this.session)){
            String resource = "mybatisconfig.xml";

            Reader inputStream = null;
            try {

                inputStream = Resources.getResourceAsReader(resource);
                SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
                SqlSessionFactory ssf = ssfb.build(inputStream);
                this.session = ssf.openSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return this.session;
    }

    /**
     * 查询全部dept
     * @return
     */
    public List<Dept> showAllWithDept(){
        return this.getSession().selectList("dept.sel2");
    }

    public List<Dept> showAllWithDept1(Dept dept){
        return this.getSession().selectList("dept.sel3",dept);
    }

    public List<EmpAndDept> showTwo(){
        return this.getSession().selectList("dept.towtable");
    }

    public List<Dept> dynamicSql(Dept dept){
        return this.getSession().selectList("dept.dynamicSql",dept);
    }

    public List<Dept> dynamicSql1(List<Integer> ids){
        return this.getSession().selectList("dept.sel4",ids);
    }

    public static void main(String[] args) {
        DeptDao deptDao = new DeptDao();

        Dept dept = new Dept();
        dept.setDeptno(20);
//        dept.setDname("RES");
        List<Integer> ids = new ArrayList<>();
        ids.add(10);
        ids.add(20);
        ids.add(30);
        deptDao.dynamicSql1(ids);
        deptDao.dynamicSql1(Arrays.asList(10,20,30));
        deptDao.getSession().close();
    }



}
